package com.rpc.consumer;


import com.rpc.center.discover.client.DiscoverServiceFactory;
import com.rpc.center.discover.client.RPCDiscoverService;
import com.rpc.common.entity.request.DiscoverDTO;
import com.rpc.common.entity.HostInfoPair;
import com.rpc.common.entity.request.PackageType;
import com.rpc.consumer.client.ConsumerConfigure;
import com.rpc.consumer.invoker.RPCConsumerInvokerHandler;
import com.rpc.center.discover.client.manager.ServerAddressManager;
import com.sun.istack.internal.NotNull;
import com.sun.tools.javac.code.Type;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.StringUtils;

import java.lang.reflect.Proxy;
import java.util.List;

@Setter
@Getter
public class RPCConsumer {
    private String interfaceName;
    private String version;
    private String group;
    private RPCDiscoverService serverDiscover;

    public void init(@NotNull ConsumerConfigure configure) {
        if (StringUtils.isEmpty(interfaceName) || StringUtils.isEmpty(version) || StringUtils.isEmpty(group)) {
            throw new RuntimeException("有必填参数为空，初始化异常");
        }
        serverDiscover = DiscoverServiceFactory.getDiscoverInstance(configure.getCenterAddress(),configure.getCenterPort());
        DiscoverDTO discoverDTO = new DiscoverDTO();
        discoverDTO.setInterfaceName(interfaceName);
        discoverDTO.setVersion("1.0.0");
        discoverDTO.setPackageType(PackageType.DISCOVER_PACKAGE);
        List<HostInfoPair> serverAddressList = null;
        try {
            serverAddressList = serverDiscover.discover(discoverDTO);
        } catch (Exception e) {
            e.printStackTrace();
            RuntimeException runtimeException=new RuntimeException();
            runtimeException.initCause(e);
            throw runtimeException;
        }
        ServerAddressManager serverAddressManager = ServerAddressManager.getAddressManagerInstance();
        serverAddressManager.addAvaliableServerList(serverAddressList); //添加可用地址
    }

    public <T> T getObject(Class<T> target) throws Exception {
        if (!target.isInterface()) {
            throw new Exception("需要是一个接口而非实现类");
        }
        Object proxy = Proxy.newProxyInstance(target.getClassLoader(), new Class[]{target},
                new RPCConsumerInvokerHandler(interfaceName));
        return (T) proxy;
    }
}
